﻿//using BaiDuFaceSdk;
using ET.DBCommon.DAL;
using Microsoft.Win32;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using WPFMediaKit.DirectShow.Controls;

namespace ET.ScoreTeacherClient.Views
{
    /// <summary>
    /// FaceRegister.xaml 的交互逻辑
    /// </summary>
    public partial class FaceRegister : Window
    {
        public UserViewModel User { get; set; }
        public FaceRegister(UserViewModel m_User)
        {
            InitializeComponent();
            this.User = m_User;
        }

        private bool m_SdkInitSuccess = false;
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            this.SelectElement();
            //if (MultimediaUtil.VideoInputDevices.Length > 0)
            //    this.cameraCaptureElement.VideoCaptureDevice = MultimediaUtil.VideoInputDevices[1];
            //else
            //    MessageBox.Show("未安装任何可用摄像头");
            //Task.Run(() =>
            //{
            //    ElephantFace.Instance.LoadFaces();
            //    this.m_SdkInitSuccess = true;
            //});
        }

        private void BtnPhotoUp_Click(object sender, RoutedEventArgs e)
        {
            this.SelectElement(false);
        }

        private void BtnPhoto_Click(object sender, RoutedEventArgs e)
        {
            this.SelectElement();
        }

        private void SelectElement(bool IsSelected = true)
        {
            this.btnPhoto.Background = IsSelected ? Brushes.White : new SolidColorBrush(Color.FromRgb(221, 221, 221));
            this.btnPhotoUp.Background = IsSelected ? new SolidColorBrush(Color.FromRgb(221, 221, 221)) : Brushes.White;

            this.cameraCaptureElement.Visibility = IsSelected ? Visibility.Visible : Visibility.Collapsed;
            this.gridPhotoUp.Visibility = IsSelected ? Visibility.Collapsed : Visibility.Visible;
        }

        private void Choose_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openDlg = new OpenFileDialog();
            openDlg.Filter = "场景文件 (*.jpg)|*.jpg";
            if (openDlg.ShowDialog() != true) return;

            this.filePath.Text = openDlg.FileName;
            this.imgPhoto.Source = new BitmapImage(new Uri(openDlg.FileName, UriKind.RelativeOrAbsolute));
        }

        private void BtnExit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void BtnRegister_Click(object sender, RoutedEventArgs e)
        {
            if (!this.m_SdkInitSuccess)
            {
                MessageBox.Show("人脸识别SDK未加载完成，请稍后再试！");
                return;
            }
            byte[] buffer = null;
            if (this.cameraCaptureElement.Visibility == Visibility.Collapsed)
                buffer = File.ReadAllBytes(this.filePath.Text);
            else
            {
                // 建立目标渲染图像器，高度为前台控件实显高度，此处不能使用.width或.height属性，否则出现错误。
                // 为了避免图像抓取出现黑边现象，需要对图象进行重新测量及缩放
                RenderTargetBitmap bitmap = new RenderTargetBitmap((int)this.cameraCaptureElement.ActualWidth, (int)this.cameraCaptureElement.ActualHeight, 96, 96, PixelFormats.Default);
                //VideoCaptureElement的Stretch="Fill"
                this.cameraCaptureElement.Measure(this.cameraCaptureElement.RenderSize);
                this.cameraCaptureElement.Arrange(new Rect(this.cameraCaptureElement.RenderSize));
                // 指定图像渲染目标
                bitmap.Render(this.cameraCaptureElement);
                // 建立图像解码器。类型为jpeg
                BitmapEncoder encoder = new JpegBitmapEncoder();
                // 将当前渲染器中渲染位图作为一个位图帧加入解码器，进行解码，取得数据流。
                encoder.Frames.Add(BitmapFrame.Create(bitmap));
                // 建立内存流，将得到解码图像流写入内存流。
                using (MemoryStream stream = new MemoryStream())
                {
                    encoder.Save(stream);
                    buffer = stream.ToArray(); // 将流以文件形式存储于计算机中。
                }   // 预览效果暂停。
                this.cameraCaptureElement.Pause();
            }

            this.PhotoRegister(buffer);
        }

        private async void PhotoRegister(byte[] buffer)
        {
            //var result = await Task.Run(() => ElephantFace.Instance.UserRegisterWithDefaultGroup(this.User.UserNumber, buffer));

            //var result = await Task.Run(() =>
            //{
            //    var data = ElephantFace.Instance.GetUserInfoWithDefaultGroup(this.User.UserNumber);
            //    if (data == null || data.result.Count == 0)
            //        return ElephantFace.Instance.UserRegisterWithDefaultGroup(this.User.UserNumber, buffer);
            //    else
            //        return ElephantFace.Instance.UserUpdateWithDefaultGroup(this.User.UserNumber, buffer);
            //});
            //MessageBox.Show(result ? "注册成功！" : "注册失败！");
            //this.User.FaceRegister = result ? "已注册" : "未注册";
            //if (result)
            //    UserInfoDAL.UpdateFaceRegister(this.User.Model);
        }
    }
}
